<template>
  <div class="banner-container">
    <!-- 轮播图列表 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>轮播图管理</span>
          <el-button type="primary" @click="showCreateDialog" :icon="Plus">添加轮播图</el-button>
        </div>
      </template>

      <el-table :data="bannerList" v-loading="loading" stripe>
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column label="图片" width="150">
          <template #default="{ row }">
            <el-image 
              :src="row.imageUrl" 
              fit="cover" 
              style="width: 120px; height: 60px; border-radius: 4px;"
              :preview-src-list="[row.imageUrl]"
            />
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题" min-width="150" show-overflow-tooltip />
        <el-table-column prop="linkUrl" label="跳转链接" min-width="200" show-overflow-tooltip />
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-switch 
              v-model="row.status" 
              :active-value="1" 
              :inactive-value="0"
              @change="toggleStatus(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="editBanner(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteBanner(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新建/编辑对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="轮播图" prop="imageUrl">
          <el-upload
            class="banner-uploader"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
          >
            <img v-if="formData.imageUrl" :src="formData.imageUrl" class="banner-image" />
            <el-icon v-else class="banner-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">建议尺寸：1920x600px，大小不超过2MB</div>
        </el-form-item>
        <el-form-item label="跳转链接">
          <el-input v-model="formData.linkUrl" placeholder="请输入跳转链接（选填）" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="formData.sort" :min="0" :max="9999" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveBanner">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import request from '@/utils/request'

const bannerList = ref([])
const loading = ref(false)

const dialogVisible = ref(false)
const dialogTitle = ref('添加轮播图')
const formRef = ref(null)
const formData = reactive({
  id: null,
  title: '',
  imageUrl: '',
  linkUrl: '',
  sort: 0,
  status: 1
})

const rules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  imageUrl: [{ required: true, message: '请上传轮播图', trigger: 'change' }]
}

// 上传相关
const uploadUrl = computed(() => {
  return import.meta.env.VITE_API_BASE_URL + '/admin/upload/image'
})

const uploadHeaders = computed(() => {
  return {
    Authorization: `Bearer ${localStorage.getItem('adminToken')}`
  }
})

// 获取轮播图列表
const getBannerList = async () => {
  loading.value = true
  try {
    const response = await request.get('/admin/banner/list')
    if (response.code === 0) {
      bannerList.value = response.data
    }
  } catch (error) {
    ElMessage.error('获取轮播图列表失败')
  } finally {
    loading.value = false
  }
}

// 显示创建对话框
const showCreateDialog = () => {
  dialogTitle.value = '添加轮播图'
  formData.id = null
  formData.title = ''
  formData.imageUrl = ''
  formData.linkUrl = ''
  formData.sort = 0
  formData.status = 1
  dialogVisible.value = true
}

// 编辑轮播图
const editBanner = (row) => {
  dialogTitle.value = '编辑轮播图'
  formData.id = row.id
  formData.title = row.title
  formData.imageUrl = row.imageUrl
  formData.linkUrl = row.linkUrl
  formData.sort = row.sort
  formData.status = row.status
  dialogVisible.value = true
}

// 保存轮播图
const saveBanner = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const url = formData.id 
          ? `/admin/banner/update/${formData.id}`
          : '/admin/banner/create'
        const method = formData.id ? 'put' : 'post'
        
        const response = await request[method](url, formData)
        if (response.code === 0) {
          ElMessage.success('保存成功')
          dialogVisible.value = false
          getBannerList()
        }
      } catch (error) {
        ElMessage.error('保存失败')
      }
    }
  })
}

// 切换状态
const toggleStatus = async (row) => {
  try {
    const response = await request.put(`/admin/banner/update/${row.id}`, row)
    if (response.code === 0) {
      ElMessage.success('状态更新成功')
    } else {
      // 失败时恢复原状态
      row.status = row.status === 1 ? 0 : 1
    }
  } catch (error) {
    ElMessage.error('状态更新失败')
    row.status = row.status === 1 ? 0 : 1
  }
}

// 删除轮播图
const deleteBanner = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除此轮播图吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await request.delete(`/admin/banner/delete/${id}`)
    if (response.code === 0) {
      ElMessage.success('删除成功')
      getBannerList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 上传前检查
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 上传成功
const handleUploadSuccess = (response) => {
  if (response.code === 0) {
    formData.imageUrl = response.data.url
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(response.message || '上传失败')
  }
}

onMounted(() => {
  getBannerList()
})
</script>

<style scoped>
.banner-container {
  padding: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.banner-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
}

.banner-uploader:hover {
  border-color: #409eff;
}

.banner-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 360px;
  height: 180px;
  text-align: center;
  line-height: 180px;
}

.banner-image {
  width: 360px;
  height: 180px;
  display: block;
  object-fit: cover;
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
}
</style>
